//
//  RequestManager.swift
//  LearningLanguage
//
//  Created by Rae on 2023/9/7.
//

import UIKit
import Alamofire
import HandyJSON

private let NetWorkRequestShareInstance = RequestManger()

class RequestManger:NSObject{
    class var sharedInstance:RequestManger {
        return NetWorkRequestShareInstance
    }
}

        
extension RequestManger{

    class func uploadImgRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()) {
        
        ToastTool.show()
        
        let headers:HTTPHeaders = ["content-type":"multipart/form-data"]
        let PathUrl = BaseUrl + UrlString
        

        AF.upload(multipartFormData: { multipartforData in
            let flag = params!["file"]
            multipartforData.append(flag as! Data, withName: "file", fileName: "avatar.jpg", mimeType: "image/jpeg")
        }, to: PathUrl, headers: headers).response{ response in
            switch response.result {
            case .success(let data):
                if let da = data {
                    do {
                        if let json = try JSONSerialization.jsonObject(with: da, options: []) as? [String: Any] {
                            print("请求结果：\n\(json)\n==========================")
                            if let dataJson = json["data"] as? [String:Any] {
                                let initializeModel = try? JSONSerialization.data(withJSONObject: dataJson, options: [])
                                print("requestsuccess===---   ")
                                print("\(dataJson)")
                                if initializeModel != nil {
                                    success(dataJson as [String : AnyObject])
                                    ToastTool.dismiss()
                                    return
                                }
                            }
                        }
                    } catch {
//                        ToastTool.toast(dict!["msg"] as! String, status: .error)
                        ToastTool.toast(error.localizedDescription, status: .error)
                    }

                }
            case .failure(let error):
                print(error)
            }
        }
    }

    
//    class func uploadAudioRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()) {
//        
//        ToastTool.show()
//        let headers = ["content-type":"multipart/form-data"]
//        let PathUrl = BaseUrl + UrlString
//        
//        AF.upload(multipartFormData: { (multipartforData) in
//            let flag = params!["file"]
//            multipartforData.append(flag as! Data, withName: "file", fileName: "audio.m4a", mimeType: "m4a")
//        }, to: PathUrl,
//           headers: headers,
//           encodingCompletion: { encodingResult in
//            switch encodingResult {
//            case .success(let upload, _, _):
//                upload.responseJSON { response in
//                    if let value = response.result.value as? [String: AnyObject]{
//                        let dict = value
//                        if let dataDict = dict["data"] as? [String : Any] {
//                            let jsonData = try? JSONSerialization.data(withJSONObject: dataDict, options: [])
//                            if jsonData != nil {
//                                success(dataDict as [String : AnyObject])
//                                ToastTool.dismiss()
//                                return
//                            }
//                        }
//                    }
//                }
////                ToastTool.dismiss()
//            case .failure(let encodingError):
//                print(encodingError)
//            }
//        }
//        )
//
//
//    }
    class func postRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:String)->(),failure:@escaping(_ error:Error)->()) {
        
        
        let para:[String:Any] = params!
        let PathUrl = BaseUrl + UrlString
        
        let appidStr = UserModel().getUUID()
        let screenStr = "\(CGFloat.screenWidth)*\(CGFloat.screenHeight)"
        let modelStr = UserModel().iphoneType()
        let str = "\(UserModel.getTimeCHUO())"

        let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        var localPara:[String:Any] = ["appid":appidStr,
                                      "channel":"default","from":"ios","net":"Wifi","os":UIDevice.current.systemVersion,"model":modelStr,"screen":screenStr,"timestamp":str,"version":appVersion ?? "1.0.0","appPackage":"Candyi215"]
        for (k, v) in para {
            localPara.updateValue(v, forKey: k)
        }
        let appinfoStr = "Candyi215#".appending(appVersion ?? "1.0.0")
        let headers:HTTPHeaders = ["Content-Type" : "application/json","appinfo":appinfoStr]
        
        print("localPara===-----   ")
        print(localPara)

        ToastTool.show()
        AF.request(PathUrl, method: .post, parameters: localPara, encoding: JSONEncoding.default,
                   headers: headers).response{ response in
            
            switch response.result{
                case .success(let data):
                
                if let data = data {
                    do {
                        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {                            
                            let dataJson = json["data"]
                            print("请求结果：\n\(dataJson)\n==========================")
                            let initializeModel = try? JSONSerialization.data(withJSONObject: dataJson as Any, options: [])
                            let jsonStr = NSString(data: initializeModel!, encoding: String.Encoding.utf8.rawValue)
                            print("requestsuccess===---   ")
                            if jsonStr != nil {
                                ToastTool.dismiss()
                                success(jsonStr! as String)
                                return
                            }
                        }
                    } catch {
//                        ToastTool.toast(dict!["msg"] as! String, status: .error)
                        ToastTool.toast(error.localizedDescription, status: .error)
                    }
                    
                } else {
                    let error = NSError(domain: "接口错误:\(PathUrl)", code: 0, userInfo: [NSLocalizedDescriptionKey: "No data"])
                    print(error)
                }
                
                    
                case .failure(let encodingError):
                ToastTool.dismiss()
                    print(encodingError)
            }
        }
    }
        
}

